/**
 * 云静Admin父页面
 */
layui.use(['jquery', 'yunj', 'layer', 'element', 'md5'], function () {
    let win = window;
    let doc = document;
    let $ = layui.jquery;
    let layer = layui.layer;
    let element = layui.element;
    let md5 = layui.md5;

    class YunjPage {

        constructor() {
            this.version = '1.0.0';
            // 页面选项卡filter标识
            this.page_tab_filter_mark = 'xbs_tab';
            // 左边菜单收起来时，鼠标移上去显示提示框的索引index
            this.left_nav_tips_index = null;

            this.init();
        }

        init() {
            let that = this;

            that.set_event_bind();
        }

        set_event_bind() {
            let that = this;
            //菜单下的li点击时触发
            $('.left-nav #nav').on('click', 'li', function (e) {
                //当菜单收起来时点击打开
                if ($('.left-nav').css('width') === '60px') {
                    $('.left-nav').animate({width: '220px'}, 100);
                    $('.page-content').animate({left: '220px'}, 100);
                    $('.left-nav i').css('font-size', '14px');
                    $('.left-nav cite,.left-nav .nav_right').show();
                }

                //去除所有a标签的active
                $('.left-nav').find('a').removeClass('active');
                //添加当前li下一层的子元素a，添加active
                $(this).children('a').addClass('active');

                //如果当前li下有子菜单则展开
                if ($(this).children('.sub-menu').length) {
                    if ($(this).hasClass('open')) {
                        $(this).removeClass('open');
                        $(this).find('.nav_right').html('&#xe603;');
                        $(this).children('.sub-menu').stop(true, true).slideUp();
                        $(this).siblings().children('.sub-menu').slideUp();
                    } else {
                        $(this).addClass('open');
                        $(this).children('a').find('.nav_right').html('&#xe61a;');
                        $(this).children('.sub-menu').stop(true, true).slideDown();
                        $(this).siblings().children('.sub-menu').stop(true, true).slideUp();
                        $(this).siblings().find('.nav_right').html('&#xe603;');
                        $(this).siblings().removeClass('open');
                    }
                }

                //阻止冒泡
                e.stopPropagation();
            });

            //左边菜单收起来时，鼠标移上去显示提示框的索引index
            $('.left-nav #nav').on('mouseenter', '.left-nav-li', function (e) {
                if ($('.left-nav').css('width') !== '220px') {
                    let tips = $(this).attr('lay-tips');
                    that.left_nav_tips_index = layer.tips(tips, $(this));
                }
            });
            //左边菜单收起来时，鼠标移开删除对应索引index的显示提示框
            $('.left-nav #nav').on('mouseout', '.left-nav-li', function (e) {
                layer.close(that.left_nav_tips_index);
            });

            //顶部控制菜单栏的展开和收起
            $('.container .left_open i').click(function (event) {
                if ($('.left-nav').css('width') === '220px') {
                    $('.left-nav .open').click();
                    $('.left-nav i').css('font-size', '18px');
                    $('.left-nav').animate({width: '60px'}, 100);
                    $('.left-nav cite,.left-nav .nav_right').hide();
                    $('.page-content').animate({left: '60px'}, 100);
                    $('.page-content-bg').hide();
                } else {
                    $('.left-nav').animate({width: '220px'}, 100);
                    $('.page-content').animate({left: '220px'}, 100);
                    $('.left-nav i').css('font-size', '14px');
                    $('.left-nav cite,.left-nav .nav_right').show();
                    if ($(win).width() < 768) {
                        $('.page-content-bg').show();
                    }
                }
            });

            // 去掉默认的鼠标contextmenu事件，否则会和右键事件同时出现
            $(".layui-tab-title").on('contextmenu', 'li', function (e) {
                e.preventDefault();
            });

            // 鼠标点击 单击右键选中选项卡上的页面时，显示关闭当前/其它/全部
            $(".layui-tab-title").on('mousedown', 'li', function (e) {
                switch (e.button) {
                    case 0:
                        // 点了左键
                        break;
                    case 1:
                        // 点了滚轮，关闭
                        $(this).find('.layui-tab-close').click();
                        break;
                    case 2:
                        // 点了右键，显示关闭当前/其它/全部
                        let tab_left = $(this).position().left;
                        let tab_width = $(this).width();
                        let this_index = $(this).attr('lay-id');
                        $('#tab_right').css({'left': tab_left + tab_width / 2}).show().attr('lay-id', this_index);
                        $('#tab_show').show();
                        break;
                }
                return false;
            });

            //点击关闭当前/其它/全部时触发
            $('#tab_right').on('click', 'dd', function (event) {
                let data_type = $(this).attr('data-type');
                let lay_id = $(this).parents('#tab_right').attr('lay-id');
                if (data_type === 'this') {
                    $('.layui-tab-title li[lay-id=' + lay_id + ']').find('.layui-tab-close').click();
                } else if (data_type === 'other') {
                    $('.layui-tab-title li').eq(0).find('.layui-tab-close').remove();
                    $('.layui-tab-title li[lay-id!=' + lay_id + ']').find('.layui-tab-close').click();
                } else if (data_type === 'all') {
                    $('.layui-tab-title li[lay-id]').find('.layui-tab-close').click();
                }
                $('#tab_right').hide();
                $('#tab_show').hide();
            });

            //点击其他地方时隐藏关闭当前/其它/全部时触发面板
            $('.page-content,#tab_show,.container,.left-nav').click(function (event) {
                $('#tab_right').hide();
                $('#tab_show').hide();
            });

            // 设置主题
            $('.set-theme').on('click', function () {
                let setBtnEl = $(this);
                layer.open({
                    type: 5,
                    title: '主题设置',
                    shade: 0.2,
                    area: ['295px', '90%'],
                    offset: 'rb',
                    maxmin: true,
                    shadeClose: true,
                    closeBtn: false,
                    anim: 2,
                    content: $('#theme_tpl').html(),
                    success: function (layero, index) {
                        yunj.theme.set_theme_tpl_active();
                        $('.theme-box li').on('click', function () {
                            yunj.theme.set($(this).data('code'));
                            yunj.close(index);
                        });
                    }
                });
                return false;
            });
        }

        /**
         * 页面id
         * @param url
         */
        page_id(url) {
            let that = this;
            url = url.substr(0, 4) === 'http' ? url : location.protocol + "//" + location.host + url;
            return md5(url);
        }

        /**
         * 打开tab子页面
         * @param {string|object} url              页面地址
         * object:{
         *      url:"",
         *      title:"",
         *      rawPage:""
         * }
         * @param {string} title     页面标题
         * @param {string|null} rawPage    源页面标识
         * @return {void}
         */
        openTab(url, title = "", rawPage = null) {
            let that = this;
            let args = yunj.objSupp(yunj.isObj(title) ? title : {
                url: url,
                title: title,
                rawPage: rawPage
            }, {
                url: "",
                title: "",
                rawPage: null
            });
            let tabFilter = that.page_tab_filter_mark;
            let tabId = that.page_id(args.url);

            //判断点击页面是否已打开
            for (let i = 0, len = $('.x-iframe').length; i < len; i++) {
                if ($('.x-iframe').eq(i).attr('tab-id') === tabId) {
                    element.tabChange(tabFilter, tabId);
                    return;
                }
            }

            // 关掉弹窗页面
            layer.closeAll();

            // 判断是否携带源页面标识
            if (args.rawPage) args.url = yunj.urlPushParam(args.url, "rawPage", args.rawPage);

            //新增tab iframe子页面
            element.tabAdd(tabFilter, {
                title: args.title,
                content: `<iframe tab-id="${tabId}" frameborder="0" src="${args.url}" scrolling="yes" class="x-iframe"></iframe>`,
                id: tabId
            });

            //切换选中
            element.tabChange(tabFilter, tabId);
            $(`.layui-tab-title li[lay-id=${tabId}] .layui-tab-close`).unbind('click').on('click', function (e) {
                that.closeTab(tabId);
                e.stopPropagation();
            });
        };

        /**
         * 打开popup子页面
         * @param {string|object} url              页面地址
         * object:{
         *      url:"",
         *      title:"",
         *      rawPage:"",
         *      w:null,
         *      h:null
         * }
         * @param {string} title     页面标题
         * @param {string|null} rawPage    源页面标识
         * @param {string|int|null} w       [指定宽]（可选，可设置百分比或者像素，像素传入int）
         * @param {string|int|null} h       [指定高]（可选，同上）
         * @return {void}
         */
        openPopup(url, title = "", rawPage = null, w = null, h = null) {
            let that = this;
            let args = yunj.objSupp(yunj.isObj(title) ? title : {
                url: url,
                title: title,
                rawPage: rawPage,
                w: w,
                h: h
            }, {
                url: "",
                title: "",
                rawPage: null,
                w: null,
                h: null
            });


            let area = 'auto';
            if (args.w !== null && h !== null) {
                args.w = args.w.toString();
                args.h = args.h.toString();
                area = [args.w.indexOf('%') !== -1 ? args.w : `${args.w}px`, args.h.indexOf('%') !== -1 ? args.h : `${args.h}px`];
            } else {
                area = ['80%', '80%'];
            }
            let param = {isPopup: "yes"};
            args.url = yunj.urlPushParam(args.url, param);
            let layerArgs = {
                id: that.page_id(url),
                type: 2,
                title: args.title,
                content: args.rawPage ? yunj.urlPushParam(args.url, "rawPage", args.rawPage) : args.url,
                skin: "popup-page",
                area: area,
                closeBtn: 1,
                shadeClose: true,
                shade: 0.2,
                maxmin: true,
                success: function (layero, index) {
                    //弹出后的回调
                },
                end: function () {
                    //销毁后的回调
                }
            };
            // 关掉其他的弹窗页面
            layer.closeAll();
            return layer.open(layerArgs);
        };

        /**
         * 关闭指定tab_id子页面（兼容移动端关闭后显示空白的问题）
         * @param tab_id
         */
        closeTab(tab_id) {
            let that = this;
            let currIdx = $(`.layui-tab-title li[lay-id=${tab_id}]`).index();
            let tabLiLen = $(".layui-tab-title li").length;
            let showIdx = currIdx < (tabLiLen - 1) ? currIdx + 1 : currIdx - 1;
            $('.layui-tab-title li').eq(showIdx).click();
            element.tabDelete(that.page_tab_filter_mark, tab_id);
        }

        /**
         * 重定向到指定tab子页面
         * @param tab_id    [默认null指向首页]
         * @returns {*}
         */
        redirectTab(tab_id = null) {
            let that = this;
            $(`.layui-tab-title li${tab_id === null ? '.home' : '[lay-id=' + tab_id + ']'}`).click();
            return tab_id;
        }

        // 当前显示tab页面的page_id
        currTabPageId() {
            let that = this;
            let ttlEl = $('.layui-tab-title li.layui-this');
            if (ttlEl.length <= 0) return null;
            let layID = ttlEl.eq(0).attr('lay-id');
            return layID && yunj.isString(layID) ? layID : null;
        }

        // 当前显示popup页面的page_id
        currPopupPageId(popup_page_el = null) {
            let that = this;
            popup_page_el = popup_page_el || $(".layui-layer-iframe.popup-page");
            if (popup_page_el.length <= 0) return null;
            return popup_page_el.find(".layui-layer-content").eq(0).attr("id");
        }

        // TODO 弃用
        // 当前显示页面是否为tab
        // curr_page_is_tab() {
        //     let that = this;
        //     return $("body.index").length <= 0 && $(".layui-layer-iframe.popup-page").length <= 0 && $('.layui-tab-title li.layui-this').length > 0;
        // }

        // 弃用
        // 当前显示页面是否为popup
        // curr_page_is_popup() {
        //     let that = this;
        //     return $(".layui-layer-iframe.popup-page").length > 0;
        // }

        // 弃用
        // 当前页面的page_id
        // currPageId() {
        //     let that = this;
        //     return that.curr_page_is_popup() ? that.currPopupPageId() : that.currTabPageId();
        // }

    }

    win.yunj.page = new YunjPage();

});